$(document).ready(function() {
	
	$('#parentCompany').typeahead([{                              
	    name: 'leadSearch',
	    valueKey: 'parentCompany',
	    header: '<legend>Leads</legend>',
	    remote: {
	        url: 'contactCompanies?query=%QUERY&parentType=lead',
	        filter: function (parsedResponse) {
	            return parsedResponse;
	        }
	    },                                             
	    template: [                                                                 
	        '<p>{{parentCompany}}</p>'
	    ].join(''),                                                                 
	    engine: Hogan                                                 
	},{                              
	    name: 'accountSearch',
	    valueKey: 'parentCompany',
	    header: '<legend>Accounts</legend>',
	    remote: {
	        url: 'contactCompanies?query=%QUERY&parentType=account',
	        filter: function (parsedResponse) {
	            return parsedResponse;
	        }
	    },                                             
	    template: [                                                                 
	        '<p>{{parentCompany}}</p>'
	    ].join(''),                                                                 
	    engine: Hogan                                                 
	}]);
	
	$('#parentCompany').bind('typeahead:selected', function(obj, datum) {        
		$('input[name=viewType]').val(datum.parentType);
    	$('input[name=parentId]').val(datum.id);
    	$('input[name=parentName]').val(datum.name);
	});

	$("#contactForm").validate({
		rules: {
			fName: "required",
			parentCompany: {
				required: true
			}
			,phone: {
				required: true,
				remote: "validator/checkContactPhone?contactId=0",
				number:true
			},
			mobile: {
				number:true
			},
			email: {
				email: true
			}
		},
		messages: {
			fName: {required : $("input#fNameRequired").val()},
			parentCompany: {
				required: $("input#companyRequired").val()
			}
			,phone: {
				required: $("input#phoneRequired").val(),
				 remote: $("input#phoneChecked").val(),
			    number: jQuery.format($("input#numbersFormat").val())
			},
			mobile: {
			    number: jQuery.format($("input#numbersFormat").val())
			},
			email: {
				email: $("input#emailFormat").val()
			}
		},
		errorPlacement: function(error, element) {
			error.appendTo(element.next());
		},
		submitHandler: function() {
			 form.submit();
		}
	});
	
	cancelButtonHandler();
});

/**
 * Cancel button handler
 */
function cancelButtonHandler(){
	$("#cancelButton").click(function() {
		document.location.href='contacts';
	});	
}

